__author__ = 'dracher'
import httplib
import base64
import time
import socket

class HttpException(Exception):
    """
    base
    """

class ConnectionError(HttpException):
    """
    Can't connect to device
    """


def sendHTTPRequest(method, url, host, port='8080', content=None, password=None, ifnonematch=None, retries=3, pause = 0, s_flag=1):
    """

    """
    returnDict = {}

    headers = {}

    HTTPS_FLAG = s_flag


    assert retries >= 0, 'retries must be greater than or equal to 0'

    # Always include Connection: Keep-Alive in the header.
    headers['Connection'] = 'Keep-Alive'

    # If there is a password, base-64 encode it.
    #Authorization:Basic (admin:password)   -- base64 encoded..

    #password = "admin:abc"
    if None != password:
        authString = 'Basic %s' % base64.b64encode(password)
        headers['Authorization'] = authString

    # If there is an IF-NONE-MATCH tag, include it.
    if None != ifnonematch:
        headers['If-None-Match'] = ifnonematch

    headers['Content-Type'] = 'text/xml'
    if content != None:
        headers['Content-Length'] = str(len(content))

    # Make sure the for loop executes at least once.
    retries = retries or 1

    for attempt in range(0, retries):
        # Send the request:
        try:
            # Open a connection.
            # httpsFlag = 1 is used to test HTTPS redirection over a secure connection
            if HTTPS_FLAG == 1:

                http_conn = httplib.HTTPSConnection(host,timeout=30)
            else:
                # IP connection

                http_conn = httplib.HTTPConnection(host, port, strict=True, timeout=30)

            http_conn.request(method, url, content, headers)
            # pause added wait for a reponse when there needs to be between method and checking for a response
            time.sleep(pause)
            httpResponse = http_conn.getresponse()



            returnDict['httpstatus'] = httpResponse.status
            returnDict['httpreason'] = httpResponse.reason
            # print "#"*60
            # print httpResponse.msg
            # print "#"*60
            returnDict['httpheader'] = httpResponse.msg

            # We don't expect any content from the device with PUTs, POSTs, and
            # DELETEs, and can only expect content with a 200 OK.
            if method == 'GET' and httpResponse.status == 200:
                responseContent = httpResponse.read()
		# print "@"*60
                # print responseContent
                # print "@"*60
            else:
                responseContent = None

            # This keeps us from returning an empty string. We should pick either
            # '' or None to return from our functions.
            returnDict['content'] = responseContent or None

            # If we got here, then the request was sent and response received.
            break;

        except (httplib.HTTPException, socket.error), info:
            # The device didn't respond, or some other equally critical exception
            # Sleep 10 seconds, if another retry is pending.
            if attempt < retries - 1:
                print('%s: Error connecting to device: %s. Trying again in 10 seconds...' % (__name__, info), 3)
                time.sleep(10)
            else:
                print('%s: Error connecting to device: %s.' % (__name__, info), 3)

        finally:
            # Close the connection.
            http_conn.close()

    return returnDict
